package com.java.study.common.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author jiangli
 */
@Data
public class JwtUtil {

    private static final String KEY = "JL-BOOT" ;

    private static final long TTL = 3600000 ; //单位s

    /**
     * 生成JWT
     *
     * @param id
     * @param subject
     * @return
     */
    public static String createJWT(String id, String subject, String headImg) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, KEY)
                .claim("head_img", headImg);
        if (TTL > 0) {
            builder.setExpiration( new Date( nowMillis + TTL));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public static Claims parseJWT(String jwtStr){
        try {
            return  Jwts.parser()
					.setSigningKey(KEY)
					.parseClaimsJws(jwtStr)
					.getBody();
        } catch (ExpiredJwtException e) {
            //过期返回null
            return null;
        }
    }

}
